import React, {useEffect, useMemo, useState} from 'react';
import type {MenuProps} from "antd";
import {Menu, Layout} from "antd";
import {DatabaseOutlined, HomeOutlined} from "@ant-design/icons";
import {useLocation, useNavigate} from "react-router-dom";
import {renderMenuItem} from "@/routes";
const {Sider} = Layout;
type MenuItem = Required<MenuProps>['items'][number];
function getItem(
    label: React.ReactNode,
    key: React.Key,
    icon?: React.ReactNode,
    children?: MenuItem[],
): MenuItem {
    return {
        key,
        icon,
        children,
        label,
    } as MenuItem;
}
function IndexSider() {
    const [collapsed,setCollapsed] = useState<boolean>(false);
    const navigate = useNavigate();
    const {pathname} = useLocation();
    const items:MenuItem[]= useMemo(()=>{
        return renderMenuItem().map((item:any)=>{
            let childrenItem;
            if(item.children){
                // [getItem(undefined,undefined),getItem("数字字典","/cmn/dict"))]
                childrenItem = item.children.filter((v:any)=>!v.isHide).map((item:any)=>{
                    return getItem(item.label,item.path);
                })
            }
            return getItem(item.label,item.path,item.icon,childrenItem);
        });
    },[]);
    // 1- 获取/ 下的路由path
    // console.log(pathname);// /cmn/dict
    // console.log(pathname.split("/"));// ["","cmn","dict"]
    // console.log(pathname.split("/")[1]);// cmn
    // console.log("/"+pathname.split("/")[1]);// /cmn
    const [keys,setKeys] = useState<string>("/"+pathname.split("/")[1]);
    // 2- 将获取的path作为keys状态的值
    useEffect(()=>{
        setKeys("/"+pathname.split("/")[1]);
    },[pathname])


    return (
        <Sider breakpoint={"md"} collapsible collapsed={collapsed} onCollapse={value => setCollapsed(value)}>
            <div className="logo">
                <img src={require("@/assets/img/logo.png")} alt=""/>
                <span style={{display: collapsed ? "none" : "inline-block"}}>尚医通管理系统</span>
            </div>
            <Menu onClick={({key})=>{
                // console.log(e.key);
                navigate(key);
            }} theme="dark"
                  // 当前展开的 SubMenu 菜单项 key 数组
                  openKeys={[keys]}
                  // SubMenu 展开/关闭的回调
                  onOpenChange={(openKeys: string[])=>{
                      // console.log(openKeys)
                      setKeys(openKeys[1]);
                  }}
                  defaultSelectedKeys={[pathname]} mode="inline" items={items}/>
        </Sider>
    );
}

export default IndexSider;